﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using DH.Web.Controllers;
using DH.Entity;
using DH.Service.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using DH.Service.Domain.User;
using DH.Core;
using DH.Web.MVC.Extensions;
using DH.Web.Filter;
using DH.Web.Attributes;
using DH.Service.Domain;

namespace DH.Web.MVC.Controllers
{
    [Authorize]
    [Route("User")]
    [Resource("用户(资源)")]
    [Guid("9838bdc9-b0e5-4387-ace0-da3d1a09000a")]
    public class UserController : SiteController<UserEntity, UserViewModel, string>
    {
        protected UserService _userService;
        
        static Logger Logger = LogManager.GetCurrentClassLogger();
        public UserController(IServiceCollection serviceCollection,
                              UserService userService) : base(serviceCollection, userService)
        {
            _userService = userService;
            
        }

        [HttpGet]
        [Route("Index")]
        [UIView("用户管理首页")]
        [Guid("9a78c592-62a8-4b93-b5b4-179945034939")]
        public IActionResult Index()
        {
            ViewBag.CurrentUser = CurrentUserEx;
            ViewBag.CurrentViewId = "9a78c592-62a8-4b93-b5b4-179945034939";
            return View();
        }

        
        [Route("Users")]
        [HttpGet]
        [Function("获取用户列表")]
        [Guid("a60c6231-1934-4e8e-ba52-75c01455c2e8")]
        public async  Task<IActionResult> GetUserList()
        {
            PagedData<UserViewModel> models;
            var pagination= GetPagination();
            var queryKey = Request.Query["queryKey"][0];
            var orgId = Request.Query["treeId"][0];
            var res =await _userService.GetListAsync(queryKey, orgId, pagination);
            models = res.ToViewModelPageData<UserEntity, UserViewModel>();

            var result = new { total = models.TotalCount, rows = models.DataList };
            return Json(result);
        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("Add")]
        [Function("添加用户",isManage:true)]
        [Guid("da16057b-50ff-4a06-8142-e308d00d9959")]
        public async  Task<IActionResult> AddUser(UserViewModel input)
        {
            if (!ModelState.IsValid)
            {
                return ErrorMessage("实体类验证失败");
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(input.Id))
                {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.UpdatedOn = DateTimeOffset.Now;

                    await _userService.EditAsync(input);
                }
                else
                {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.CreatedBy = CurrentUser.UserId;
                    await _userService.AddAsync(input);
                }

                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("新增用户发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", nameof(UserViewModel));
            }
        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("Delete")]
        [Function("删除用户",isManage:true)]
        [Guid("aba9da52-b4a9-4e4e-9e15-2fa91efc325f")]
        public async Task<IActionResult> DeleteUsers(string[] ids) {
            try
            {
                await _userService.DeleteAsync(ids);
                ///todo:删除用户相关
                ///删除用户权限
                ///删除用户菜单
                ///删除用户角色

                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("删除用户发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", ids);
            }
        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("EnabledUser")]
        [Function("启用用户",isManage:true)]
        [Guid("18ded418-3bf3-4501-a4ea-6c20f9fbc061")]
        public async Task<IActionResult> EnabledUser(string id) {
            try
            {
                await _userService.EnabledUserAsync(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("启用用户发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", id);
            }
        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("DisabledUser")]
        [Function("禁用用户",isManage:true)]
        [Guid("aa3abb0e-bc36-49a6-a951-92c877aaebb6")]
        public async Task<IActionResult> DisabledUser(string id)
        {
            try
            {
                await _userService.DisabledUserAsync(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("禁用用户发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", id);
            }
        }

        [HttpGet]
        [Route("GetUtiltityUsers")]
        [Function("获取公用弹窗用户")]
        [Guid("490fb38a-6285-4f10-ba7d-881bc0a2b4cd")]
        public async  Task<IActionResult> GetUtilityUsers() {
            var res =await _userService.GetFullPathUserAsync();
            return new JsonResult(res);
        }

        [HttpGet]
        [Route("GetUserInfo")]
        [Function("获取用户个人信息")]
        [Guid("f0838dff-5f77-4eeb-8c9d-16d58cb025b5")]
        public async Task<IActionResult> GetUserInfo()
        {
            try {
                var userId = CurrentUserEx.UserId;
                var userInfo = await _userService.GetUserInfoAsync(userId);
                
                return new JsonResult(new {status=200,data=userInfo,msg="" });

            } catch (Exception ex)
            {
                return new JsonResult(new {status=500,data="",msg=ex.Message });
            }
            

        }


        [HttpGet]
        [Route("CheckUserExisted")]
        [Function("检查用户userId是否已存在")]
        [Guid("5ad9fc33-b3b8-45d3-b178-085f26a37d63")]
        public async  Task<IActionResult> CheckUserIdExist(string userId,string id)
        {
            try {
                var res = await _userService.CheckExistUserIdAsync(userId, id);
                return new JsonResult(new { status = 200, data = res, msg = "" });

            } catch (Exception ex) {
                Logger.Error("检查用户userid发生异常：" + ex.Message);
                return new JsonResult(new { status = 500, data = false, msg = "" });
            }
        }


        [HttpPost]
        [Route("UpdateUserInfo")]
        [Function("更新个人信息")]
        [Guid("cf8f8c11-d3b9-4266-b602-4d0e1ae5d29a")]
        public async Task<IActionResult> UpdateUserInfo(string userNickName,string userSign,string userPhone,string email,string userImg)
        {
            PrivilegeService _privilegeService;
            _privilegeService = _service.BuildServiceProvider().GetService<PrivilegeService>();
            try {
               
                var userId = CurrentUserEx.UserId;
                var res =await  _userService.UpdateUserInfoAsync(userId,userNickName,userSign,userPhone,email,userImg);

                var session = new UserSession();
                session.UserId = res.DH_Account;
                session.UserName = res.DH_NickName;
                session.RealName = res.DH_RealName;
                session.IsAdmin = res.DH_IsAdministrator;
                session.DepartmentId = res.DH_DepartmentId;
                session.DutyId = res.DH_DutyId;
                session.RoleId = _privilegeService.GetUserRoles(res.Id);
                session.IsDeveloper = res.DH_IsDeveloper;
                session.UserImg = res.DH_HeadIcon;

                CurrentUser = session;

                var userSessionEx = new UserSessionEx(_service);
                userSessionEx.DepartmentId = CurrentUser.DepartmentId;
                userSessionEx.IsAdmin = CurrentUser.IsAdmin;
                userSessionEx.IsDeveloper = CurrentUser.IsDeveloper;
                userSessionEx.LoginIP = CurrentUser.LoginIP;
                userSessionEx.LoginTime = CurrentUser.LoginTime;
                userSessionEx.RealName = CurrentUser.RealName;
                userSessionEx.RoleId = CurrentUser.RoleId;
                userSessionEx.UserId = CurrentUser.UserId;
                userSessionEx.DepartmentId = CurrentUser.DepartmentId;
                userSessionEx.UserName = CurrentUser.UserName;
                userSessionEx.UserImg = CurrentUser.UserImg;

                CurrentUserEx = userSessionEx;


                return new JsonResult(new { status = 200, data = res!=null, msg = "" });
            }
            catch (Exception ex)
            {
                Logger.Error("更新用户信息发生异常：" + ex.Message);
                return new JsonResult(new { status = 500, data = false, msg = "" });
            }
        }

    }
}